<template>
  <!-- 监听弹窗关闭事件close -->
  <el-dialog :visible.sync="showDialog" :title="form.id?'编辑':'新增'" @close="resetForm">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="角色名字" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
      <el-form-item class="form-btn">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="showDialog=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addRole, editRole, getSingleRole } from '@/api/company'
export default {
  data() {
    return {
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 打开弹窗
    async  open(id) {
      if (id) {
        // 编辑员工信息
        const res = await getSingleRole(id)
        this.form = res
      }
      this.showDialog = true
    },
    // 保存角色
    async save() {
      // 校验表单
      await this.$refs.form.validate()
      // 判断 如果存在id就是编辑
      if (this.form.id) {
        await editRole(this.form)
      } else {
        // 否则就是新增调用接口
        await addRole(this.form)
      }

      // 提示保存成功
      this.$message.success('保存成功')
      // 关闭弹窗
      this.showDialog = false
      // 提示页面刷新数据
      this.$emit('reload')
    },
    // 移除表单校验及内容
    resetForm() {
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-btn{
  text-align: center;
}
</style>
